/**
 * 
 */
package io.dora.rpc;

import io.dora.remoting.ConsumerClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * RPC调用动态代理实现
 * 
 * @author zhaohongbo
 *
 */
public class RpcInvocationHandler implements InvocationHandler {

	/** 调用方客户端 */
	private ConsumerClient consumerClient;

	/** 服务KEY */
	private String serviceKey;
	
	public RpcInvocationHandler(String serviceKey, ConsumerClient consumerClient) {
		this.serviceKey = serviceKey;
		this.consumerClient = consumerClient;
	}

	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		if (consumerClient == null) {
			throw new RuntimeException("No provider host found for service:" + serviceKey);
		}
		
		String methodName = method.getName();
        Class<?>[] parameterTypes = method.getParameterTypes();
        System.out.println("method.getDeclaringClass()=" + method.getDeclaringClass());
        if (method.getDeclaringClass() == Object.class) {
            return method.invoke(this, args);
        }
        if ("toString".equals(methodName) && parameterTypes.length == 0) {
            return this.toString();
        }
        if ("hashCode".equals(methodName) && parameterTypes.length == 0) {
            return this.hashCode();
        }
        if ("equals".equals(methodName) && parameterTypes.length == 1) {
            return this.equals(args[0]);
        }
		
		RpcInvocation invocation = new RpcInvocation();
		invocation.setMethodName(method.getName());
		invocation.setParameters(args);
		invocation.setParameterTypes(method.getParameterTypes());
		invocation.setServiceKey(serviceKey);
		FutureResult futureResult = consumerClient.request(invocation);
		return futureResult.get();
	}

}
